package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JPanel;
import javax.swing.Timer;

import sim.Blob;
import sim.TorusMath;
import sim.Vec2;
import sim.World;

public class WorldDisplayPanel extends JPanel implements ActionListener, ComponentListener, MouseListener
{
	private final World world;
    private Long timestamp;
    private Timer timer = null;
    private BlobSelectionListener listener;
    public WorldDisplayPanel(World world,BlobSelectionListener listener)
    {
    	this.world = world;
    	this.listener = listener;
        setPreferredSize(new Dimension(400,400));
        addComponentListener(this);
        addMouseListener(this);
    }
    
    
    @Override
    public void paint(Graphics g)
    {
    	Graphics2D g2d = (Graphics2D)g;
        world.draw(g2d);
    }

    
    @Override
    public void actionPerformed(ActionEvent event)
    {
    	world.update(0.01);
        repaint();
    }


	
    @Override
    public void componentResized(ComponentEvent event)
    {
        Vec2 lowerRight = new Vec2(getWidth(),getHeight());
    	world.setEnvSize(new Vec2(0,0),lowerRight);
    	TorusMath.instance.setxWrapPoint(lowerRight.x);
    	TorusMath.instance.setyWrapPoint(lowerRight.y);

        if(timer == null)
        {
        	timer = new Timer(0,this);
	        timer.setInitialDelay(0);
	        timer.setDelay(10);
	        timer.setRepeats(true);
	        timestamp = null;
	        timer.start();
        }
    }
	@Override
	public void mousePressed(MouseEvent event) 
	{
		if (event.getButton()==1)
		{
			Blob blob = world.getBlobAtPosition(event.getX(),event.getY());
			listener.blobSelectionChanged(blob);
		}
		if (event.getButton()==3)
		{
			world.placeFood(new Vec2(event.getX(),event.getY()));
		}		
	}
	@Override
	public void mouseClicked(MouseEvent event) 
	{
	}    
    @Override
    public void componentHidden(ComponentEvent arg0)
    {
    }
    @Override
    public void componentMoved(ComponentEvent arg0)
    {
    }
    @Override
    public void componentShown(ComponentEvent arg0)
    {
    }
    @Override
	public void mouseEntered(MouseEvent arg0) 
	{		
	}
	@Override
	public void mouseExited(MouseEvent arg0) 
	{		
	}
	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
    
    
}
